package top.lingkang.finaloauth2.client.http;

import cn.hutool.http.HttpRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import top.lingkang.finaloauth2.client.error.Oauth2HttpAccessException;

import java.util.HashMap;
import java.util.List;

/**
 * @author lingkang
 * Created by 2022/3/23
 */
public class DefaultResourceHttpAccess implements ResourceHttpAccess {
    private static final Log log = LogFactory.getLog(DefaultResourceHttpAccess.class);

    @Override
    public String get(String url, HashMap<String, List<String>> requestHeader) {
        try {
            return HttpRequest.get(url)
                    .header(requestHeader) //头信息，多个头信息多次调用此方法即可
                    .timeout(5000) //超时，毫秒
                    .execute().body();
        } catch (Exception e) {
            log.error("连接授权服务端异常：" + url + " exception:" + e.getMessage());
            throw new Oauth2HttpAccessException("连接授权服务端异常：" + e.getMessage());
        }
    }

    @Override
    public String post(String url, HashMap<String, List<String>> requestHeader, HashMap<String, Object> requestParam) {
        try {
            return HttpRequest.post(url)
                    .header(requestHeader) //头信息，多个头信息多次调用此方法即可
                    .form(requestParam) //表单内容
                    .timeout(5000) //超时，毫秒
                    .execute().body();
        } catch (Exception e) {
            log.error(e);
            throw new Oauth2HttpAccessException(e.getMessage());
        }
    }
}
